import {
  indexApi
} from '../../api/index';
import {
  request
} from '../../utils/request';
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
const app = getApp();
Page({
  data: {


    defaultData: {
      title: "方案报价", // 导航栏标题
      // imageSrc: "/images/home.png",
      isBackToPreviousPage: false
    },
    three: true, //三图标
    tabs: 0, //选择的房间id
    keyword: '', // 用于存储用户输入的搜索关键词
    roomName: "",
    rotate: false, // 控制图片的旋转状态
    currentImageUrl: '/images/image-quick/dropDown.png', //下拉箭头
    showImageUrl: true, //显示下拉或者方块
    squareCheckedProducts: {}, //储存复选框选中
    checkedAll: false, //全选状态
    menuList: [], //服务类目
    showpopup: false, //类目显示
    showAllocation: false, //显示配置
    sanPopup: false, //显示小弹框"三
    showRoomPopup: false, //显示房间弹框
    addressPop: false, //显示地址弹框
    selectedAddressId: "", //选中的地址id,
    selectedAddress: "", //选中的地址
    clickActionsMiddle: "",
    showTime: false, //日期显示
    selectedDate: '', //日期
    minDate: new Date().getTime(), //当前时间
    fileList: [], //图片上传
    serviceTypeName: null, //用户选择的类目
    serviceTypeId: null, //类目id
    inputValue: '',
    active: 0,
    isAllExpanded: false, // 用于记录是否全部展开
    isEdit: false, //用于记录是否编辑和完成
    orderId: null,
    isDelete: false, //删除的显示和隐藏
    isCommodity: true, //增加商品的显示和隐藏
    isSelectAll: false, //全选的显示和隐藏
    isExpanded: false, //全部折叠和全部展开
    isDialogVisible: false, //商品数量输入弹框
    currentProductId: null, //商品数量输入弹框临时储存id
    tempProductCount: 0, //商品数量输入弹框临时储存数量
    isMerge: true, //合并拆分
    isSplit: true, //合并拆分的显示和隐藏
    position: false, //安装位置的显示和隐藏
    stepper: true, //步进器的显示和隐藏
    productTypeNum: 0, //商品种类数量
    productCount: 0, //商品数量
    showInput: false, //群组的显示
    showPosition: false, //位置弹框
    show: false,
    tabsRoom: [],
    expandedProducts: {},
    productLocation: [], //下拉列表安装位置
    allLocation: [], //全部安装位置
    locationList: [], //过滤后的安装位置
    locationRadio: null, //单选框选择的位置
    selectedLocation: '入门位置',
    locationId: null,
    ProductProperty: [], //下拉列表产品属性
    selectedProperty: '请选择',
    propertyId: null,
    pageNum: 1,
    pageSize: 12,
    Management: false, //方案管理弹框
    pgeName: "", //方案名称
    managementList: [], //方案数组
    managementRadio: "", // 当前选中的方案 ID
    isDel: 0, //是否删除方案
    isEditModify: false, // 是否为编辑模式
    selectedPgeName: "", // 选中方案的名称
    selectedManagement: {}, //选中的一条方案
    managementName: "未设置方案", //信息统计的方案名
    saveManagement: true, //是否是保存方案
    saveManagementID: null,
    nowManagement: {} //当前方案
  },

  onLoad(options) {
    if (typeof this.getTabBar == 'function') {
      this.getTabBar((tabBar) => {
        tabBar.setData({
          selected: 1
        })
      });
    }
    //登录
    this.checkToken();
    //安装位置
    this.getLocationAll()
    this.getProductProperty()
    //获取默认房间
    console.log("options.fromRoom", options.fromRoom);
    if (options.fromRoom) {
      this.getFromHouseType()
    } else {
      this.getDefaultHouseType()
    }

    //一起类目直接选择维修服务
    this.getOneSeverAll()
    //方案管理
    this.getManagement()
  },

  onShow() {
    const app = getApp();
    const selectedProducts = app.globalData.selectedProducts || [];
    if (selectedProducts.length > 0) {
      this.updateGoods(selectedProducts);
      app.globalData.selectedProducts = []; // 重置全局数据以避免重复添加
    }

    if (app.globalData.roomList.rooms && app.globalData.roomList.rooms.length > 0) {
      this.handleConfirm()
    }
  },

  // 方案管理弹框
  showManagement() {
    if (!this.data.isEditModify && !this.data.roomList.selectedAddress) {
      Toast('请到方案配置里面填写客户信息');
      return;
    }
    this.setData({
      Management: true,
      pgeName: this.data.isEditModify ? this.data.selectedPgeName : "", // 如果是编辑模式，设置为选中方案的名称
    });
  },

  // 保存方案
  showManagementPop() {
    console.log("this.data.saveManagement", this.data.saveManagement);
    if (this.data.saveManagement) {
      // 第一次保存，弹出输入框
      this.showManagement();
    } else {
      // 直接保存，不弹框
      this.saveTemplate();
    }
  },

  // 另存方案
  saveAs() {
    this.setData({
      isEditModify: true,
    })
    this.showManagement();
  },

  // 编辑方案
  managementModify(event) {
    const {
      id,
    } = event.currentTarget.dataset; // 获取点击的项的 id 和名称
    const name = event.currentTarget.dataset.managementitem.pgeName
    console.log("event.currentTarget.dataset", event.currentTarget.dataset);
    this.setData({
      managementRadio: id, // 更新选中的单选按钮的值
      isEditModify: true, // 设置为编辑模式
      selectedPgeName: name, // 设置选中方案的名称
      selectedManagement: event.currentTarget.dataset.managementitem, //整条方案
      pgeName: this.data.isEditModify
    });
    // 显示弹框并填入当前方案名称
    this.showManagement();
  },

  // 删除方案
  deleteItem() {
    const {
      managementList,
      managementRadio
    } = this.data;
    if (managementRadio !== "") {
      Dialog.confirm({
          title: '确定要删除此房间吗',
        })
        .then(() => {
          const newProgrammeEntity = managementList.find((item) => item.id == managementRadio);
          const isDel = 1;
          newProgrammeEntity.isDel = isDel;
          console.log("programmeEntity", newProgrammeEntity);
          this.saveTemplate(newProgrammeEntity);

        })
        .catch(() => {
          // 取消删除的逻辑
          console.log('取消删除');
        });
    } else {
      wx.showToast({
        title: "请先选择一个方案",
        icon: "none",
      });
    }
  },


  // 打开方案
  openManagement() {
    const {
      selectedManagement
    } = this.data
    console.log("选中的方案", selectedManagement);
    this.setData({
      nowManagement:selectedManagement
    })
    this.replaceData()
  },



  // 关闭方案弹框
  ManagementClose() {
    this.setData({
      Management: false,
      pgeName: "", // 关闭时清空方案名
      isEditModify: false, // 重置编辑模式
    });
  },

  // 输入方案名称
  pgeNameChange(event) {
    console.log("输入方案名称", event);
    this.setData({
      pgeName: event.detail,
    });
  },

  // 确定方案名
  onConfirmAddRoom() {
    const pgeName = this.data.pgeName;
    console.log("方案名", pgeName);
    if (!pgeName.trim()) {
      wx.showToast({
        title: '方案名称不能为空',
        icon: 'none',
      });
      return;
    }
    // 检查方案名是否重复
    const isDuplicate = this.data.managementList.some((item) => item.pgeName === pgeName);
    if (isDuplicate) {
      wx.showToast({
        title: '方案名称已存在',
        icon: 'none',
      });
      return;
    }

    this.saveTemplate(); // 更新方案
    // 保存或更新方案
    // if (this.data.isEditModify) {
    //   this.saveTemplate(); // 更新方案
    // } else {
    //   this.saveTemplate(); // 保存新方案
    // }
  },

  // 选中方案
  managementChange(event) {
    const {
      selectedManagement
    } = this.data.selectedManagement
    this.setData({
      managementRadio: event.detail,
      selectedManagement: event.currentTarget.dataset.managementitem
    });
    console.log("选中方案", event);
  },



  // 替换数据
  replaceData() {
    const {
      nowManagement,
      roomList
    } = this.data;

    console.log("roomList", roomList);

    const {
      roomEntityList,
      pgeName,
      addressId,
      serviceTypeId,
      addressEntity,
      houseTypeItem
    } = nowManagement;

    console.log("addressId", addressId);
    console.log("替换数据里面的id", roomEntityList);

    // 房间tabsRoom
    const rooms = roomEntityList.map(room => {
      return {
        ...room,
        tid: room.id, // 添加tid属性，保留id
        roomName: room.roomName,
        roomLocation: room.roomLocation,
        goods: room.roomProductEntityList.map(product => {
          return {
            ...product,
            // tid: product.productId, // 添加tid属性，保留productId
            count: product.count,
            selectedLocationIndex: product.locationId,
            productId: product.productId,
            debuggingPrice: product.debuggingPrice,
            productPrice: product.productPrice,
            installationPrice: product.installationPrice,
            serviceFee: product.serviceFee,
            ...product.product
          };
        })
      };
    });

    // 将 rooms 添加到 houseTypeItem 中
    let updatedHouseTypeItem = {
      ...houseTypeItem,
      rooms
    };

    // 将 updatedHouseTypeItem 赋值给 roomList
    let updatedRoomList = {
      ...updatedHouseTypeItem
    };

    console.log("替换数据", updatedRoomList);

    // 判断 updatedRoomList 中是否存在 selectedAddress
    if (updatedRoomList.selectedAddress) {
      // 如果存在，则更新 addressId
      updatedRoomList.selectedAddress = addressEntity;
    } else {
      // 如果不存在，则添加 selectedAddress
      updatedRoomList.selectedAddress = {
        ...addressEntity
      };
    }

    console.log("rooms", rooms);
    const firstRoomId = rooms[0].tid;

    this.setData({
      tabsRoom: rooms,
      serviceTypeId: serviceTypeId, // 正确的 serviceTypeId
      roomList: updatedRoomList,
      pgeName: pgeName,
      tabs: firstRoomId,
      isEditModify: false,
      saveManagement: false,
      // nowManagement: selectedManagement
    });

    console.log("tabsRoom", this.data.tabsRoom);
    console.log("roomList", this.data.roomList);
    console.log("tabs", this.data.tabs);
    console.log("当前方案", this.data.nowManagement);
  },



  // 保存方案
  async saveTemplate(newProgrammeEntity) {
    const {
      pgeName,
      selectedManagement,
      saveManagementID,
      managementName,
      saveManagement
    } = this.data;

    let programmeEntity;
    // 判断 newProgrammeEntity 是否存在
    if (newProgrammeEntity) {
      programmeEntity = newProgrammeEntity;
    } else {
      if (this.data.isEditModify) {
        console.log("方案名", pgeName);
        console.log("整条方案", selectedManagement);
        selectedManagement.pgeName = pgeName;
        programmeEntity = selectedManagement;
      } else {
        // 新增
        console.log("不是编辑");
        let {
          tabsRoom,
          roomList,
          serviceTypeId,
          pgeName,
          nowManagement
        } = this.data;
        console.log("测试tabsRoom", tabsRoom);
        // 拼接 programmeEntity
        const roomEntityList = tabsRoom.map(room => {
          const roomEntity = {
            roomName: room.roomName,
            roomLocation: room.roomLocation,
            roomProductEntityList: room.goods.map(product => {
              // 对商品进行条件判断
              const productEntity = {
                count: product.count,
                locationId: product.selectedLocationIndex,
                productId: product.productId,
                debuggingPrice: product.debuggingPrice,
                productPrice: product.productPrice,
                installationPrice: product.installationPrice,
                serviceFee: product.serviceFee
              };

              // 如果有 product.id，则添加到 productEntity 中
              if (product.id) {
                console.log("添加id");
                productEntity.id = product.id;
              }

              return productEntity;
            })
          };

          // 对房间进行条件判断
          if (room.id) {
            roomEntity.id = room.id;
          }
          return roomEntity;
        });
        console.log("roomEntityList", roomEntityList);

        // 户型
        programmeEntity = {
          serviceTypeId,
          addressId: roomList.selectedAddress.addressId,
          pgeName: pgeName,
          roomEntityList
        };

        // 对户型 ID 进行条件判断
        if (Object.keys(nowManagement).length > 0) {
          programmeEntity.id = nowManagement.id;
          programmeEntity.pgeName = nowManagement.pgeName;
         
      }
      

        console.log("programmeEntity", programmeEntity);
      }
    }

    // 统一接口调用逻辑
    try {
      const res = await request({
        url: indexApi.saveOrUpdateProgrammesApi(),
        method: "POST",
        data: programmeEntity
      });
      console.log("接口返回的方案=======", res);

      if (this.data.saveManagement) {
        this.setData({
          managementName: res.data.pgeName,
          saveManagementID: res.data.id,
          saveManagement: false,
          // selectedManagement: res.data,
          managementRadio: res.data.id,
          nowManagement: res.data
        });
        console.log("保存", this.data.selectedManagement);
      }
      this.getManagement();
      this.replaceData();
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //获取方案管理名称
  async getManagement() {
    const reqSearch = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize
    }
    try {
      const res = await request({
        url: indexApi.getUserProgrammesApi(),
        method: "POST",
        data: reqSearch
      });
      this.setData({
        managementList: res.data
      })
      console.log("方案管理名称", res.data);

    } catch (error) {
      console.error("Error:", error);
    }
  },

  //发布订单
  async releaseOrders() {
    console.log("tabsRoom", this.data.tabsRoom);
    let {
      serviceTypeId,
      selectedAddressId,
      tabsRoom,
      selectedDate
    } = this.data;
    // 检查所有 tabsRoom 中的 goods 是否全部为空
    const allGoodsEmpty = tabsRoom.every(room => room.goods.length == 0);
    if (allGoodsEmpty) {
      Toast('请新增商品');
      return;
    }
    if (!selectedDate) {
      Toast('请先选择预约时间');
      return
    }
    if (!selectedAddressId) {
      Toast('请先选择地址');
      return
    }

    const transformedData = tabsRoom.map(room => {
      return {
        roomName: room.roomName,
        children: room.goods.map(product => {
          return {
            productId: product.productId,
            productName: product.productName,
            count: product.count,
            skillsVo: [{}],
            locationId: this.data.locationId,
            propertyId: this.data.propertyId
          };
        })
      };
    });

    const requestData = {
      addressId: selectedAddressId,
      service_time: selectedDate,
      children: transformedData,
    };

    try {
      const res = await request({
        url: indexApi.releaseOrdersApi(serviceTypeId),
        method: "POST",
        data: requestData
      });
      console.log("releaseOrdersApi", res.data.orderId);
      this.setData({
        order: res.data.orderId
      })
      const orderId = res.data.orderId
      this.getOrderByOrder(orderId)
    } catch (error) {
      console.error("Error:", error);
    }
  },



  // 获取默认房间
  async getDefaultHouseType() {
    console.log("从上个页面进来", app.globalData.roomList);
    try {
      const res = await request({
        url: indexApi.getDefaultHouseTypeApi(),
        data: {}
      });

      const {
        allLocation
      } = this.data;
      console.log("房间的id", res.data);

      const firstRoomId = res.data.rooms[0].id; // 获取第一个房间的原始 id
      const roomList = res.data;

      // 遍历每个房间并替换 id 为 tid，同时添加需要的字段
      const updatedHouse = {
        ...roomList,
        rooms: roomList.rooms.map(room => ({
          ...room,
          tid: room.id, // 新增 tid 属性
          id: undefined, // 将 id 属性设为 undefined
          productCount: 0,
          productTypeNum: 0,
          goods: [],
          positions: allLocation, // 将安装位置数据直接赋值给房间的 positions 属性
        })).map(room => {
          delete room.id; // 删除 id 属性
          return room;
        })
      };
      // const firstRoomId = res.data.rooms[0].tid; // 获取第一个房间的原始 id

      this.setData({
        tabsRoom: updatedHouse.rooms,
        roomList: updatedHouse,
        tabs: firstRoomId, // 继续使用原始 id 作为 tabs 的初始值
      });

      console.log("默认房间", this.data.tabsRoom);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //获取导入的房间
  getFromHouseType() {
    console.log("从方案配置干活来的", app.globalData.roomList);
    const roomList = app.globalData.roomList
    const firstRoomId = roomList.rooms[0].tid;
    this.setData({
      roomList: roomList,
      tabsRoom: roomList.rooms,
      tabs: firstRoomId
    })
  },

  // //获取全部的位置
  // async getLocationAll() {
  //   try {
  //     const res = await request({
  //       url: indexApi.getLocationApi(),
  //       data: {}
  //     });

  //     // 遍历res.data数组，为每个对象添加checked字段
  //     const updatedLocationAll = res.data.map(item => ({
  //       ...item,
  //       checked: false // 初始化为未选中状态
  //     }));

  //     // 更新页面数据
  //     this.setData({
  //       allLocation: updatedLocationAll
  //     });
  //   } catch (error) {
  //     console.error("Error:", error);
  //   }
  // },

  // //获取用户选择的房间
  handleConfirm: function () {
    this.setData({
      tabsRoom: app.globalData.roomList.rooms,
      roomList: app.globalData.roomList,
      tabs: app.globalData.roomList.rooms[0].tid,
    });
    // app.globalData.roomList = [];
    console.log("app.globalData.roomList", this.data.tabsRoom);
    console.log("app.globalData.roomList", app.globalData.roomList);
  },


  //更新房间下面的商品
  updateGoods(selectedProducts) {
    const {
      tabsRoom,
      tabs
    } = this.data;
    const updatedTabsRoom = [...tabsRoom];
    const currentRoom = updatedTabsRoom.find(room => room.tid === tabs);
    console.log("currentRoom", currentRoom);
    selectedProducts.forEach((product, index) => {
      if (this.data.isMerge) {
        const existingProductIndex = currentRoom.goods.findIndex(good => good.productId === product.productId);
        if (existingProductIndex !== -1) {
          currentRoom.goods[existingProductIndex].count += product.count;
        } else {
          currentRoom.goods.push({
            ...product,
            productLocation: [],
            splitIndex: currentRoom.goods.length + '-' + index
          });
        }
      } else {
        for (let i = 0; i < product.count; i++) {
          currentRoom.goods.push({
            ...product,
            count: 1,
            productLocation: [],
            splitIndex: currentRoom.goods.length + '-' + (index * product.count + i)
          });
        }
      }
    });

    // 统计商品种类数和商品总数量
    const uniqueProductIds = new Set(currentRoom.goods.map(product => product.productId));
    currentRoom.productTypeNum = uniqueProductIds.size;
    currentRoom.productCount = currentRoom.goods.reduce((total, product) => total + product.count, 0);

    this.setData({
      tabsRoom: updatedTabsRoom
    });

    console.log("更新后的商品：", this.data.tabsRoom);
  },


  //获取产品属性
  async getProductProperty() {
    try {
      const res = await request({
        url: indexApi.getProductPropertyApi(),
        data: {}
      });
      this.setData({
        ProductProperty: res.data
      })
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //安装位置的选择
  locationChange(event) {
    const selectedLocationId = event.detail; // 获取选择的位置ID
    const selectedLocationObj = this.data.allLocation.find(location => location.id === selectedLocationId); // 根据ID查找对应的位置对象
    const selectedLocation = selectedLocationObj ? selectedLocationObj.title : '默认位置'; // 获取选择的位置名称，若未找到则默认位置
    const {
      currentSplitIndex,
      currentRoomId,
      tabsRoom
    } = this.data; // 获取当前选择的商品splitIndex、房间ID和tabsRoom数据

    // 遍历房间查找对应的商品并更新其位置
    const updatedTabsRoom = tabsRoom.map(room => {
      if (room.tid == currentRoomId) {
        return {
          ...room,
          goods: room.goods.map(product => {
            if (product.splitIndex === currentSplitIndex) {
              return {
                ...product,
                selectedLocation,
                selectedLocationIndex: selectedLocationId
              };
            }
            return product;
          })
        };
      }
      return room;
    });


    // 更新页面数据
    this.setData({
      tabsRoom: updatedTabsRoom,
      locationRadio: selectedLocationId, // 更新 locationRadio 的值
      showPosition: false
    });
    console.log("tabsRoom", this.data.tabsRoom);
  },

  //可选的安装位置
  showPositionChange(event) {
    const splitIndex = event.currentTarget.dataset.splitindex; // 获取当前选择的商品splitIndex
    const roomId = event.currentTarget.dataset.tid; // 获取当前选择的房间ID
    const {
      tabsRoom
    } = this.data; // 获取tabsRoom数据

    let currentProduct = null;
    let currentRoom = tabsRoom.find(room => room.tid == roomId); // 根据ID找到对应的房间

    if (currentRoom) {
      currentProduct = currentRoom.goods.find(product => product.splitIndex === splitIndex); // 找到对应的商品

      if (currentProduct) {
        const roomLocationIds = currentRoom.roomLocation.split(",").map(Number); // 将roomLocation转换为数字数组

        // 根据roomLocation匹配allLocation并构建locationList
        const locationList = this.data.allLocation.filter(location =>
          roomLocationIds.includes(location.id)
        ).map(location => ({
          ...location,
          checked: location.id === currentProduct.selectedLocationIndex // 确保只有当前商品的选中位置被设置为选中状态
        }));

        // 更新页面数据
        this.setData({
          showPosition: true,
          locationList: locationList,
          currentSplitIndex: splitIndex, // 存储当前商品的splitIndex
          currentRoomId: roomId, // 存储当前房间的ID
          locationRadio: currentProduct.selectedLocationIndex // 设置当前商品的位置ID
        });

        console.log("locationList=======", this.data.locationList);
      } else {
        console.error("未找到对应的商品");
      }
    } else {
      console.error("未找到对应的房间");
    }
  },


  // 在页面初始化时获取全部位置数据
  async getLocationAll() {
    try {
      const res = await request({
        url: indexApi.getLocationApi(),
        data: {}
      });

      // 遍历res.data数组，为每个对象添加checked字段
      const updatedLocationAll = res.data.map(item => ({
        ...item,
        checked: false // 初始化为未选中状态
      }));

      // 更新页面数据
      this.setData({
        allLocation: updatedLocationAll
      });
    } catch (error) {
      console.error("Error:", error);
    }
  },


  // 合并拆分
  toggleMergeSplit(e) {
    // const id = e.currentTarget.dataset.id;
    // const id = this.data.tabs;
    const {
      tabsRoom,
      isMerge
    } = this.data;
    const room = tabsRoom.find(room => room.tid == this.data.tabs);

    if (room && room.goods.length > 0) {
      if (isMerge) {
        // 拆分逻辑
        const newGoodsList = [];
        room.goods.forEach((item, index) => {
          if (item.count > 1) {
            for (let i = 0; i < item.count; i++) {
              newGoodsList.push({
                ...item,
                count: 1,
                splitIndex: index + '-' + i,
                selectedLocation: item.productLocation && item.productLocation[i] ? item.productLocation[i].location : '默认位置',
                selectedLocationIndex: item.productLocation && item.productLocation[i] ? item.productLocation[i].index : 0
              });
            }
          } else {
            newGoodsList.push({
              ...item,
              splitIndex: index + '-0',
              selectedLocation: item.selectedLocation || '默认位置',
              selectedLocationIndex: item.selectedLocationIndex || 0
            });
          }
        });

        // 对商品进行排序，将相同位置的商品放在一起，默认位置排在最后
        newGoodsList.sort((a, b) => {
          if (a.selectedLocationIndex !== b.selectedLocationIndex) {
            return a.selectedLocationIndex - b.selectedLocationIndex; // 按位置索引排序
          } else {
            return a.selectedLocation === '默认位置' ? 1 : b.selectedLocation === '默认位置' ? -1 : 0;
          }
        });

        const expandedProducts = {};
        newGoodsList.forEach(product => {
          expandedProducts[product.splitIndex] = false;
        });

        this.setData({
          tabsRoom: tabsRoom.map(room => (room.tid == this.data.tabs ? {
            ...room,
            goods: newGoodsList
          } : room)),
          expandedProducts,
          isMerge: !this.data.isMerge,
          stepper: !this.data.stepper,
          position: !this.data.position,
          productCount: newGoodsList.reduce((total, product) => total + product.count, 0),
          productTypeNum: new Set(newGoodsList.map(product => product.productId)).size,
          isAllExpanded: false,
          isExpanded: false,
        });
        console.log("拆分", this.data.tabsRoom);
      } else {
        // 合并逻辑
        const mergedGoods = [];
        const goodsMap = {};
        room.goods.forEach(item => {
          const key = item.productId;
          if (goodsMap[key]) {
            goodsMap[key].count += item.count;
            goodsMap[key].productLocation.push({
              location: item.selectedLocation,
              index: item.selectedLocationIndex
            });
          } else {
            goodsMap[key] = {
              ...item,
              count: item.count,
              productLocation: [{
                location: item.selectedLocation,
                index: item.selectedLocationIndex
              }]
            };
          }
        });

        for (const key in goodsMap) {
          mergedGoods.push(goodsMap[key]);
        }

        // Reset expanded states for all products
        const expandedProducts = {};
        mergedGoods.forEach(product => {
          expandedProducts[product.splitIndex] = false;
        });

        this.setData({
          tabsRoom: tabsRoom.map(room => (room.tid == this.data.tabs ? {
            ...room,
            goods: mergedGoods
          } : room)),
          expandedProducts,
          isMerge: !this.data.isMerge,
          stepper: !this.data.stepper,
          position: !this.data.position,
          productCount: mergedGoods.reduce((total, product) => total + product.count, 0),
          productTypeNum: new Set(mergedGoods.map(product => product.productId)).size,
          isAllExpanded: false,
          isExpanded: false,
        });

        console.log("合并", this.data.tabsRoom);
      }
    } else {
      Toast('没有可拆分的商品');
    }
  },



  //产品属性选择
  bindPickerProperty(event) {
    const PropertyIndex = event.detail.value
    const selectedPropertyTitle = this.data.ProductProperty[PropertyIndex].title;
    const propertyId = this.data.ProductProperty[PropertyIndex].id;
    this.setData({
      selectedProperty: selectedPropertyTitle,
      propertyId: propertyId
    })
  },


  // 切换tab
  handleCustomTab(event) {
    const tid = event.currentTarget.dataset.tid;
    this.setData({
      tabs: tid
    });
  },

  // 减少商品
  reduce(event) {
    const productId = event.currentTarget.dataset.productid;
    const {
      tabsRoom,
      tabs
    } = this.data;
    // 根据id获取当前房间
    const currentRoom = tabsRoom.find(room => room.tid === tabs);
    const productIndex = currentRoom.goods.findIndex(product => product.productId === productId);
    if (productIndex !== -1) {
      if (currentRoom.goods[productIndex].count > 1) {
        currentRoom.goods[productIndex].count -= 1;
      }
    }
    // 更新商品总数量
    currentRoom.productCount = currentRoom.goods.reduce((total, product) => total + product.count, 0);
    this.setData({
      tabsRoom
    });
  },

  // 加商品
  add(event) {
    const productId = event.currentTarget.dataset.productid;
    const {
      tabsRoom,
      tabs
    } = this.data;
    // 根据id获取当前房间
    const currentRoom = tabsRoom.find(room => room.tid === tabs);
    const productIndex = currentRoom.goods.findIndex(product => product.productId === productId);
    if (productIndex !== -1) {
      currentRoom.goods[productIndex].count += 1;
    }
    // 更新商品总数量
    currentRoom.productCount = currentRoom.goods.reduce((total, product) => total + product.count, 0);

    this.setData({
      tabsRoom
    });
  },
  // 输入商品数量
  onInputChange(event) {
    const value = parseInt(event.detail.value, 10);
    this.setData({
      tempProductCount: isNaN(value) ? 0 : value,
    });
  },

  // 商品数量输入的弹框
  clickInput(event) {
    const currentProductId = event.currentTarget.dataset.productid;
    this.setData({
      isDialogVisible: true,
      currentProductId,
    });
  },

  // 确认输入的数量并关闭弹框
  onDialogConfirm() {
    const {
      tabsRoom,
      tabs,
      tempProductCount,
      currentProductId
    } = this.data;

    // 根据id获取当前房间
    const currentRoom = tabsRoom.find(room => room.tid === tabs);
    const productIndex = currentRoom.goods.findIndex(product => product.productId == currentProductId);
    if (productIndex !== -1) {
      currentRoom.goods[productIndex].count = tempProductCount;
    }
    // 更新商品总数量
    currentRoom.productCount = currentRoom.goods.reduce((total, product) => total + product.count, 0);
    this.setData({
      isDialogVisible: false,
      tabsRoom,
    });
  },

  toProductList() {
    if (this.data.serviceType == null) {
      Toast('请先选择类目');
    } else {
      const serviceType = this.data.serviceType;
      const serviceTypeStr = encodeURIComponent(JSON.stringify(serviceType));
      wx.navigateTo({
        url: `/packageOrder/pages/product/index?serviceTypeName=${serviceTypeStr}`,
      });
    }
  },


  // 单个折叠面板
  handleDropDown(event) {
    const splitIndex = event.currentTarget.dataset.splitindex; // 使用 splitIndex
    this.setData({
      [`expandedProducts.${splitIndex}`]: !this.data.expandedProducts[splitIndex]
    });
    this.checkAllExpanded();
  },

  // 检查用户有没有手动全部展开或全部折叠
  checkAllExpanded() {
    let allExpanded = true;
    let allCollapsed = true;
    this.data.tabsRoom.forEach(room => {
      room.goods.forEach(product => {
        const splitIndex = product.splitIndex;
        if (this.data.expandedProducts[splitIndex]) {
          allCollapsed = false;
        } else {
          allExpanded = false;
        }
      });
    });

    this.setData({
      isAllExpanded: allExpanded,
      isExpanded: allExpanded // 更新图片旋转状态
    });

    if (!allExpanded && allCollapsed) {
      this.setData({
        isAllExpanded: false,
        isExpanded: false // 更新图片旋转状态
      });
    }
  },

  // 全部展开或折叠
  toggleExpandAll(event) {
    const tid = event.currentTarget.dataset.tid;
    const room = this.data.tabsRoom.find(room => room.tid == tid);
    if (room && room.goods.length > 0) {
      const isAllExpanded = !this.data.isAllExpanded;
      const expandedProducts = {};
      this.data.tabsRoom.forEach(room => {
        room.goods.forEach(product => {
          const splitIndex = product.splitIndex;
          expandedProducts[splitIndex] = isAllExpanded;
        });
      });

      this.setData({
        expandedProducts,
        isAllExpanded,
        isExpanded: isAllExpanded // 更新图片旋转状态
      });
    } else {
      Toast('没有可展开的商品');
    }


  },

  //点击编辑
  handleImageUrl(event) {
    const tid = event.currentTarget.dataset.tid;
    // 找到对应 id 的房间
    const room = this.data.tabsRoom.find(room => room.tid == tid);
    // 如果找到房间且房间有商品
    if (room && room.goods.length > 0) {
      this.setData({
        showImageUrl: !this.data.showImageUrl,
        isEdit: !this.data.isEdit,
        isDelete: !this.data.isEdit,
        isSelectAll: !this.data.isSelectAll,
        isCommodity: !this.data.isCommodity,
        isSplit: !this.data.isSplit,
        sanPopup: false
      });
    } else {
      Toast('没有可编辑的商品');
    }
  },


  // 单选
  squareChange(e) {
    const index = e.currentTarget.dataset.index;
    const checked = e.detail;
    this.setData({
      squareCheckedProducts: {
        ...this.data.squareCheckedProducts,
        [index]: checked
      }
    }, this.updateCheckAllStatus);
  },

  // 全选
  handleCheckAll(e) {
    const checkedAll = e.detail;
    const roomId = e.currentTarget.dataset.tid
    const squareCheckedProducts = {};
    this.data.tabsRoom.find(room => room.tid === roomId).goods.forEach((item, index) => {
      squareCheckedProducts[index] = checkedAll;
    });
    this.setData({
      checkedAll,
      squareCheckedProducts
    });
  },

  // 单选全部被选中更改全选状态
  updateCheckAllStatus() {
    const currentGoods = this.data.tabsRoom.find(room => room.tid === this.data.tabs).goods;
    const allChecked = currentGoods.every((item, index) => this.data.squareCheckedProducts[index]);
    this.setData({
      checkedAll: allChecked
    });
  },

  // 删除
  handleDelete() {
    const hasCheckedProduct = Object.values(this.data.squareCheckedProducts).some(value => value);
    if (!hasCheckedProduct) {
      Toast('您还没有选择商品');
      return;
    }
    Dialog.confirm({
      title: '确认删除吗',
    }).then(() => {
      // 根据id获取当前房间
      const currentRoom = this.data.tabsRoom.find(room => room.tid === this.data.tabs);
      const updatedGoods = currentRoom.goods.filter((item, index) => !this.data.squareCheckedProducts[index]);

      currentRoom.goods = updatedGoods;

      // 更新商品种类数和商品总数量
      const uniqueProductIds = new Set(currentRoom.goods.map(product => product.productId));
      currentRoom.productTypeNum = uniqueProductIds.size;
      currentRoom.productCount = currentRoom.goods.reduce((total, product) => total + product.count, 0);

      if (updatedGoods.length < 1) {
        this.setData({
          tabsRoom: this.data.tabsRoom,
          squareCheckedProducts: {},
          checkedAll: false,
          showImageUrl: false,
          isExpanded: false,
          isEdit: !this.data.isEdit,
          isDelete: !this.data.isEdit,
          isSelectAll: !this.data.isSelectAll,
          isCommodity: !this.data.isCommodity,
          isSplit: !this.data.isSplit,
        });
      } else {
        this.setData({
          tabsRoom: this.data.tabsRoom,
          squareCheckedProducts: {},
          checkedAll: false,
        });
      }
      console.log("删除后的房间数据：", this.data.tabsRoom);
    }).catch(() => {
      // 取消删除
    });
  },

  // 输入框内容改变事件
  inputChange: function (e) {
    this.setData({
      keyword: e.detail.value
    });
  },
  // 搜索按钮点击事件
  search: function () {
    const keyword = this.data.keyword;
  },

  //日期
  showDatetimePicker() {
    this.setData({
      showTime: true
    });
  },
  onConfirm(event) {
    const timestamp = event.detail; // 获取时间戳
    const date = new Date(timestamp); // 使用时间戳创建Date对象
    const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // 格式化日期和时间
    this.setData({
      showTime: false,
      selectedDate: formattedDate // 更新selectedDate为格式化后的日期和时间
    });
  },
  onCancel() {
    this.setData({
      showTime: false
    });
  },
  timeClose() {
    this.setData({
      showTime: false
    });
  },

  //上传图片
  afterRead(event) {
    const {
      file
    } = event.detail;
    this.uploadFile(file);
  },

  // 文件超出大小限制处理函数
  onOversize(event) {
    wx.showToast({
      title: '文件大小超出限制',
      icon: 'none'
    });
  },

  // 上传图片
  async uploadFile(file) {
    try {
      const uploadTask = wx.uploadFile({
        url: indexApi.upLoadApi(),
        header: {
          "Content-Type": "multipart/form-data"
        },
        filePath: file.url,
        name: 'file',
        formData: {

        },
        success: (res) => {
          const data = JSON.parse(res.data);
          this.setData({
            fileList: [...this.data.fileList, file]
          });
        },
        fail: (err) => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      });
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 删除图片
  onDelete(event) {
    const {
      index
    } = event.detail;
    const {
      fileList
    } = this.data;
    fileList.splice(index, 1); // 删除对应索引的文件
    this.setData({
      fileList
    });
  },


  // 显示类目弹框
  showCategory() {
    this.setData({
      showpopup: true,
      three: false
    })
    this.getSeverAll()
  },
  onClose() {
    this.setData({
      showpopup: false,
      addressPop: false,
      three: true,
      isDialogVisible: false,

    });
  },
  closePosition() {
    this.setData({
      showPosition: false,

    });
  },
  showPopup() {
    this.setData({
      showpopup: true
    });
  },
  //选择类目
  navigateToServePage(event) {
    const serviceType = event.currentTarget.dataset.category
    const serviceTypeId = event.currentTarget.dataset.category.serviceTypeId
    this.setData({
      showpopup: false,
      serviceTypeName: serviceType.serviceTypeName,
      serviceType: serviceType,
      serviceTypeId,
      three: true
    });
  },

  // 一期类目，默认是维修服务

  //显示群组

  //显示配置弹窗
  MoreConfigurations() {
    this.setData({
      showAllocation: true,
      three: false
    })
  },
  moreClose() {
    this.setData({
      showAllocation: false,
      three: true
    });
  },
  // 小弹框
  handleSan: function () {
    // 点击图标时打开弹框
    this.setData({
      sanPopup: true
    });
  },

  // 给整个页面添加点击事件，点击页面其他位置时关闭弹框
  handleTapOutside: function (event) {
    if (event.target.dataset.sanPopup !== 'true' && event.target.dataset.showRoomPopup !== 'true') {
      this.setData({
        sanPopup: false,
        showRoomPopup: false
      });
    }
  },

  //  房间弹框
  handleRoom() {
    this.setData({
      sanPopup: false
    }, () => {
      console.log('sanPopup set to false', this.data.sanPopup);
      this.setData({
        showRoomPopup: true,
        three: false,
      }, () => {});
    });
  },

  //跳到户型页面
  toHouseType() {
    const app = getApp(); // 获取小程序实例
    this.setData({
      'roomList.rooms': this.data.tabsRoom
    });
    console.log("roomList.rooms", this.data.roomList);
    app.globalData.roomList = this.data.roomList; // 将数据存储到全局变量中
    console.log("app.globalData.roomList++++++++++++", app.globalData.roomList);
    wx.navigateTo({
      url: '/packageOrder/pages/houseType/index',
    })
  },

  roomClose() {
    this.setData({
      showRoomPopup: false
    });
  },



  //关闭房间弹框
  handleCloseRoom() {
    this.setData({
      showRoomPopup: false,
      three: true,
    })
  },

  //二期服务类目
  async getSeverAll() {
    try {
      const res = await request({
        url: indexApi.severApi(),
        data: {}
      });
      this.setData({
        menuList: res.data
      })
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //一期服务类目
  async getOneSeverAll() {
    try {
      const res = await request({
        url: indexApi.severApi(),
        data: {}
      });
      this.setData({
        serviceTypeName: res.data[2].serviceTypeName,
        serviceTypeId: res.data[2].serviceTypeId,
        serviceType: res.data[2]
      })
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 地址弹框
  clickIcon() {
    this.setData({
      addressPop: true
    })
    const child = this.selectComponent('#myChild');
    child.getAddress();
  },
  addressClose() {
    this.setData({
      addressPop: false
    })
  },
  addressPopClose(event) {
    const {
      selectedAddressId,
      selectedAddress
    } = event.detail;
    this.setData({
      addressPop: false,
      selectedAddressId,
      selectedAddress
    })
  },

  enterPopup() {
    setTimeout(() => {
      // 获取子组件实例
      const addressPopup = this.selectComponent('#myAddressPopup');
      if (addressPopup) {
        // 调用子组件的 getAddress 方法
        addressPopup.getAddress();
      } else {
        console.error('Failed to get addressPopup component');
      }
    }, 10); // 使用 setTimeout 确保子组件已经挂载完成
  },

  // 检查 token 的函数
  checkToken: function () {
    try {
      const token = wx.getStorageSync('token');
      if (token) {
        // 如果有 token，设置标记并处理登录状态
        this.setData({
          hasToken: true
        });
      } else {
        // 如果没有 token，显示登录弹框
        this.showLoginDialog();
      }
    } catch (e) {
      // 获取 token 失败时处理错误，比如提示用户或者尝试其他登录方式
      console.error('获取 token 失败：', e);
      this.showLoginDialog();
    }
  },

  showLoginDialog: function () {
    wx.showModal({
      title: '登录提示',
      content: '您还未登录，请登录以继续使用',
      showCancel: false,
      success(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/login/index',
          })
        }
      }
    });
  },


  //获取整个订单数据,展示到支付页面
  async getOrderByOrder(getOrderId) {
    // const orderId=this.data.orderId
    const orderId = getOrderId
    const reqTemplate = {
      orderId: orderId
    }
    try {
      const res = await request({
        url: indexApi.getByOrderId(),
        method: "POST",
        data: reqTemplate
      });
      const orderString = encodeURIComponent(JSON.stringify(res.data));
      wx.navigateTo({
        url: `/packageOrder/pages/orderDetails/index?order=${orderString}`
      });
    } catch (error) {
      console.error("Error:", error);
    }
  },
});